import { FOLLOW_TEACHER_LIST } from '../mutation-types';
import { getFollowTeacherList } from '../../api';

function getInitialState() {
  return {
    list: [],
    currentPage: 1,
    pageCount: 1,
    hasNextPage: null,
    loading: false,
    noData: true
  };
}

const state = getInitialState();

const getters = {
  menu: (state) => state.menu,
  list: (state) => state.list,
  loading: (state) => state.loading,
  hasNextPage: (state) => state.hasNextPage,
  noData: (state) => state.noData,
  currentPage: (state) => state.currentPage
};

const mutations = {
  [FOLLOW_TEACHER_LIST](state, payload) {
    console.log(state);
    console.log(payload);
    state.currentPage = payload.currentPage;
    state.pageCount = payload.pageCount;
    if (payload.items.length !== 0) {
      state.hasNextPage = payload.hasNextPage;
    } else {
      state.hasNextPage = null;
    }
    const oldList = state.list;
    state.list = oldList.concat(payload.items);
    state.noData = payload.noData;
    state.loading = false;
    console.log('now state: -> ', state);
  },
  loading(state) {
    state.loading = true;
  },
  destroyedState(state) {
    state = Object.assign(state, getInitialState());
    console.log('destroyed state: -> ', state);
  }
};

const actions = {
  // 获取分类列表的课程数据
  [FOLLOW_TEACHER_LIST]({ commit }, data) {
    commit({type: 'loading'});
    console.log(data);
    getFollowTeacherList(data.page, data.params)
      .then(res => {
        console.log(res);
        const currentPage = res.data.meta.currentPage;
        const pageCount = res.data.meta.pageCount;
        const hasNextPage = currentPage < pageCount && currentPage !== 0;
        commit({
          type: FOLLOW_TEACHER_LIST,
          items: res.data.items,
          currentPage: currentPage,
          pageCount: pageCount,
          hasNextPage: hasNextPage,
          noData: res.data.items.length === 0
        });
      });
  },
  // 在请求参数切换时，清空list数据
  destroyedState({ commit }) {
    commit({
      type: 'destroyedState'
    });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
